from django.shortcuts import render
import requests
from lxml import etree
from django.http import HttpResponse
import time
import re
import redis
import random
import json
from math import floor


# 随机获取cookie
def redis_cooke(cold):
    pool = redis.ConnectionPool(host='47.104.175.127', port=6379, db=cold, decode_responses=True, password='123456')
    r = redis.StrictRedis(connection_pool=pool)
    keys = r.keys()
    key = random.choice(keys)
    cookie = r.get(key)
    listCookies = json.loads(cookie)
    cookie = [item["name"] + "=" + item["value"] for item in listCookies]
    cookiestr = '; '.join(item for item in cookie)
    print(key)
    return cookiestr


# 飞猪列表查询
def list(request):
    city = request.GET.get("city")
    keywords = request.GET.get("keywords")
    check_in = request.GET.get("check_in")
    check_out = request.GET.get("check_out")
    dangcis = request.GET.get("dangcis")
    headers = {
        # 'Host': 'hotel.fliggy.com',
        # 'Connection': 'keep-alive',
        # 'Cache-Control': 'max-age=0',
        # 'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        # 'Sec-Fetch-Site': 'same-origin',
        # 'Sec-Fetch-Mode': 'navigate',
        # 'Sec-Fetch-User': '?1',
        # 'Sec-Fetch-Dest': 'document',
        # 'Referer': 'https://hotel.fliggy.com/hotel_list3.htm?_input_charset=utf-8&cityName=%E5%8C%97%E4%BA%AC&city=&keywords=&checkIn=2020-12-06&checkOut=2020-12-07',
        # 'Accept-Encoding': 'gzip, deflate, br',
        # 'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie':
            't=bdd2901394b52a20f14c52c8abb23fd9; cookie2=1a03fdd01e4805d57063354f87688b9f; cna=l5WNGNiqqSgCAdym5LAZ+BhD; chanelStat="NA=="; UM_distinctid=1771d73d9d55e2-00b95bd216276e-31346d-1fa400-1771d73d9d6aa6; VISITED_HOTEL_TOKEN=b716af80-4bd3-4291-9a31-5046ea924896; _tb_token_=f75ed393e0453; xlly_s=1; checkInDate=2021-03-19; checkOutDate=2021-03-20; CNZZDATA1253581663=647788943-1615283340-https%253A%252F%252Fhotel.fliggy.com%252F%7C1616138817; dnk=%5Cu738B%5Cu5FC3%5Cu9875; uc1=cookie15=VFC%2FuZ9ayeYq2g%3D%3D&cookie16=W5iHLLyFPlMGbLDwA%2BdvAGZqLg%3D%3D&existShop=false&cookie21=V32FPkk%2FgihExWcJfOqo&cookie14=Uoe1hMX1JkDsQQ%3D%3D&pas=0; tracknick=%5Cu738B%5Cu5FC3%5Cu9875; lid=%E7%8E%8B%E5%BF%83%E9%A1%B5; _l_g_=Ug%3D%3D; unb=970945898; cookie1=AVIlygkn4SSTRVpxh3kkUTOnQ1pkb9TfBNnLx0WNu4I%3D; login=true; cookie17=WvcQQAjUet3g; _nk_=%5Cu738B%5Cu5FC3%5Cu9875; sgcookie=E1000W6rBRZVC4TnDFDWbazRO1KhhzrB66nRIPR%2FUwd1qIvvJE0ENKepfvt03XiM%2B0%2Bw5sztu7mXiOTRO5Aj9HRdLQ%3D%3D; sg=%E9%A1%B58d; csg=e3bd0947; enc=RyBkpE3WkswHx%2BIRvMZZottRlYt1fhiMWJGy184%2FU7QHnKUdwcnpzYIbIcMXRUxiYs8euTMeAEb5oQgJAiEkrA%3D%3D; x5sec=7b22617365727665723b32223a22323965323230666535373932646534636364323137633236353665313164323643494f7330594947454a3332345944473475437161686f4c4f5463774f5451314f446b344f7a496f416a44756b764b3242513d3d227d; isg=BKurf5x0T6Z_dpOhhNQjEuDMOs-VwL9CxshSCh0ogupBvMsepZLNk3MaFvzSnBc6; tfstk=cXXGBuxeY1R1kbAhNR91fOx9TbNdZXH2rtWCLtfVZbm5jMXFiLhEaWX3xFbGHj1..; l=eBM9oNPgjjCSeYY8BOfwnurza77tsIRAguPzaNbMiOCPObfp5FxfW6w-geY9CnGVh6z2R35VLnk3BeYBqnALE-X0lFoEvcMmn'
        #     redis_cooke(15)
    }
    try:
        html = requests.get(
            f'https://hotel.fliggy.com/hotel_list3.htm?_input_charset=utf-8&_output_charset=utf-8&dangcis={dangcis}&cityName={city}&city=&keywords={keywords}&checkIn={check_in}&checkOut={check_out}',
            headers=headers)
        html_data = etree.HTML(html.text)
        lists = html_data.xpath(".//*[@id='J_List']")
        for list in lists:
            names = list.xpath("div/div/div[4]/div/h5/a/text()")
            shids = list.xpath("div/@data-shid")
            addresss = list.xpath("div/div/div[4]/div/p/a/@data-address")
            try:
                scores = list.xpath("div/div/div[3]/a/p[1]/span[1]/text()")
            except:
                scores = list.xpath("div/div/div[3]/a/p[1]/text()")
            urls = list.xpath("div/div/div[4]/div/h5/a/@href")

        hotel = [{'name': name, 'shid': shid, 'address': address, 'score': score,
                  'url': 'https:' + url + '&_output_charset=utf8&_input_charset=utf8'} for
                 name, shid, address, score, url in
                 zip(names, shids, addresss, scores, urls)]

        data_json = {
            "result": 'true',
            "msg": "",
            "data": {
                "maxPage": 1,
                "currentCount": len(hotel),
                "city": city,
                "check_in": check_in,
                "check_out": check_out,
                "hotels": hotel
            }
        }

        return HttpResponse(json.dumps(data_json))
    except:
        return HttpResponse(json.dumps({'msg': 'ture', 'code': '400', 'ms': '登陆失效'}))


# 飞猪列表地址查询
def list_path(request):
    city = request.GET.get("city")
    keywords = request.GET.get("keywords")
    check_in = request.GET.get("check_in")
    check_out = request.GET.get("check_out")
    current_page = request.GET.get("current_page")
    dangcis = request.GET.get("dangcis")
    headers = {
        # 'Host': 'hotel.fliggy.com',
        # 'Connection': 'keep-alive',
        # 'Cache-Control': 'max-age=0',
        # 'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        # 'Sec-Fetch-Site': 'same-origin',
        # 'Sec-Fetch-Mode': 'navigate',
        # 'Sec-Fetch-User': '?1',
        # 'Sec-Fetch-Dest': 'document',
        # 'Referer': 'https://hotel.fliggy.com/hotel_list3.htm?_input_charset=utf-8&cityName=%E5%8C%97%E4%BA%AC&city=&keywords=&checkIn=2020-12-06&checkOut=2020-12-07',
        # 'Accept-Encoding': 'gzip, deflate, br',
        # 'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie':
            't=bdd2901394b52a20f14c52c8abb23fd9; cookie2=1a03fdd01e4805d57063354f87688b9f; cna=l5WNGNiqqSgCAdym5LAZ+BhD; chanelStat="NA=="; UM_distinctid=1771d73d9d55e2-00b95bd216276e-31346d-1fa400-1771d73d9d6aa6; VISITED_HOTEL_TOKEN=b716af80-4bd3-4291-9a31-5046ea924896; _tb_token_=f75ed393e0453; xlly_s=1; checkInDate=2021-03-19; checkOutDate=2021-03-20; CNZZDATA1253581663=647788943-1615283340-https%253A%252F%252Fhotel.fliggy.com%252F%7C1616138817; dnk=%5Cu738B%5Cu5FC3%5Cu9875; uc1=cookie15=VFC%2FuZ9ayeYq2g%3D%3D&cookie16=W5iHLLyFPlMGbLDwA%2BdvAGZqLg%3D%3D&existShop=false&cookie21=V32FPkk%2FgihExWcJfOqo&cookie14=Uoe1hMX1JkDsQQ%3D%3D&pas=0; tracknick=%5Cu738B%5Cu5FC3%5Cu9875; lid=%E7%8E%8B%E5%BF%83%E9%A1%B5; _l_g_=Ug%3D%3D; unb=970945898; cookie1=AVIlygkn4SSTRVpxh3kkUTOnQ1pkb9TfBNnLx0WNu4I%3D; login=true; cookie17=WvcQQAjUet3g; _nk_=%5Cu738B%5Cu5FC3%5Cu9875; sgcookie=E1000W6rBRZVC4TnDFDWbazRO1KhhzrB66nRIPR%2FUwd1qIvvJE0ENKepfvt03XiM%2B0%2Bw5sztu7mXiOTRO5Aj9HRdLQ%3D%3D; sg=%E9%A1%B58d; csg=e3bd0947; enc=RyBkpE3WkswHx%2BIRvMZZottRlYt1fhiMWJGy184%2FU7QHnKUdwcnpzYIbIcMXRUxiYs8euTMeAEb5oQgJAiEkrA%3D%3D; x5sec=7b22617365727665723b32223a22323965323230666535373932646534636364323137633236353665313164323643494f7330594947454a3332345944473475437161686f4c4f5463774f5451314f446b344f7a496f416a44756b764b3242513d3d227d; isg=BKurf5x0T6Z_dpOhhNQjEuDMOs-VwL9CxshSCh0ogupBvMsepZLNk3MaFvzSnBc6; tfstk=cXXGBuxeY1R1kbAhNR91fOx9TbNdZXH2rtWCLtfVZbm5jMXFiLhEaWX3xFbGHj1..; l=eBM9oNPgjjCSeYY8BOfwnurza77tsIRAguPzaNbMiOCPObfp5FxfW6w-geY9CnGVh6z2R35VLnk3BeYBqnALE-X0lFoEvcMmn'
        #     redis_cooke(15)
    }
    try:
        html = requests.get(
            f'https://hotel.fliggy.com/hotel_list3.htm?_input_charset=utf-8&_output_charset=utf-8&dangcis={dangcis}&cityName={city}&city=&keywords={keywords}&checkIn={check_in}&checkOut={check_out}&currentPage={current_page}',
            headers=headers)
        html_data = etree.HTML(html.text)
        lists = html_data.xpath(".//*[@id='J_List']")
        for list in lists:
            names = list.xpath("div/div/div[4]/div/h5/a/text()")
            shids = list.xpath("div/@data-shid")
            addresss = list.xpath("div/div/div[4]/div/p/a/@data-address")
            lats = list.xpath("div/div/div[4]/div/p[1]/a/@data-lat")
            lngs = list.xpath("div/div/div[4]/div/p[1]/a/@data-lng")
            urls = list.xpath("div/div/div[4]/div/h5/a/@href")

        hotel = [{'name': name, 'shid': shid, 'address': address, 'lat': lat, 'lng': lng,
                  'url': 'https:' + url + '&_output_charset=utf8&_input_charset=utf8'} for
                 name, shid, address, lat, lng, url in
                 zip(names, shids, addresss, lats, lngs, urls)]

        data_json = {
            "result": 'true',
            "msg": "",
            "data": {
                "current_page": current_page,
                "currentCount": len(hotel),
                "city": city,
                "check_in": check_in,
                "check_out": check_out,
                "hotels": hotel
            }
        }

        return HttpResponse(json.dumps(data_json))
    except:
        return HttpResponse(json.dumps({'msg': 'ture', 'code': '400', 'ms': '登陆失效'}))


# 同行价格查询
def hotel_alitrip(request):
    item_id = request.GET.get("item_id")
    check_in = request.GET.get("check_in")
    check_out = request.GET.get("check_out")
    # try:
    header = {
        # 'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
        # 'Accept-Encoding': 'gzip, deflate, br',
        # 'Accept-Language': 'zh-CN,zh;q=0.9',
        # 'Connection': 'keep-alive',
        'Cookie':
            't=bdd2901394b52a20f14c52c8abb23fd9; cookie2=1a03fdd01e4805d57063354f87688b9f; cna=l5WNGNiqqSgCAdym5LAZ+BhD; chanelStat="NA=="; UM_distinctid=1771d73d9d55e2-00b95bd216276e-31346d-1fa400-1771d73d9d6aa6; VISITED_HOTEL_TOKEN=b716af80-4bd3-4291-9a31-5046ea924896; _tb_token_=f75ed393e0453; xlly_s=1; dnk=%5Cu5C0F%5Cu5C0F%5Cu6247%5Cu8D1D00; tracknick=%5Cu5C0F%5Cu5C0F%5Cu6247%5Cu8D1D00; lid=%E5%B0%8F%E5%B0%8F%E6%89%87%E8%B4%9D00; enc=wfykNHpxx%2Bd34%2FiFYws%2FwarKiXf7Z1k8%2Bx8U0yIpE1ETTq0LAldAI%2Fwr7lflnrPhrplvZt0H4ts0LVJ%2B%2F3e1%2BTBwyprJEtN0PLMD319oTo4%3D; uc1=cookie16=U%2BGCWk%2F74Mx5tgzv3dWpnhjPaQ%3D%3D&cookie15=VFC%2FuZ9ayeYq2g%3D%3D&cookie21=VFC%2FuZ9aj3yE&cookie14=Uoe1hxygKY9gBg%3D%3D&existShop=false&pas=0; _l_g_=Ug%3D%3D; unb=2200600528497; cookie1=UU8MpDDw1vxjJXsf11ew5LPT3JDjyEW8h6AXc0hVoWc%3D; login=true; cookie17=UUphyu%2BEScykLWqYgw%3D%3D; _nk_=%5Cu5C0F%5Cu5C0F%5Cu6247%5Cu8D1D00; sgcookie=E1000Nfe%2FSJtgeEW1fUSHX3v2v%2FaYVGoAiO9%2BfT5aeq4ZlgG7qBT1HmqqJkmnKbhK8alpX8ZIpppE99IvoEeylJHdg%3D%3D; sg=07e; csg=73878452; checkInDate=2021-03-13; CNZZDATA1253581663=647788943-1615283340-https%253A%252F%252Fhotel.fliggy.com%252F%7C1615537544; checkOutDate=2021-03-15; x5sec=7b226873703b32223a223264626433313536336261393039613932666265313238333439373732653536434f447772494947454961786a7153516d3937547a514561447a49794d4441324d4441314d6a67304f5463374d5367434d4b3757344c76392f2f2f2f2f77453d222c22617365727665723b32223a226162333539333137336664306638373332393134623136633638333563356431434e7a7772494947454d794b77666e316b35582f41786f504d6a49774d4459774d4455794f4451354e7a73784b41497737704c797467553d227d; isg=BIuL2dOObxkxTbMBZDQDcsBsGi91IJ-iEaFtAP2IyUohHKl-hfPw8Lm69hzyPPea; tfstk=cNolBdw434z7Wa4m53ZSF5jfF1mlZMIUsDoj0D2VCWvnRDmVihQV7EmDn7covw1..; l=eBM9oNPgjjCSeOHXBO5Cnurza7792IRbzsPzaNbMiInca6wh_FwckNCQsrjJ8dtjgtfAIetzPnnb5Rnv7zzT5K9WEEEwaIn2LJJ6-',
        # 'Referer': 'https://hotel.fliggy.com/item2.htm?spm=181.7087313.1997114781.54.7a588212FxM0jf&from=d_item&item_id=618256782369&start=2021-02-02&end=2021-02-03',
        # 'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
        # 'sec-ch-ua-mobile': '?0',
        # 'Sec-Fetch-Dest': 'empty',
        # 'Sec-Fetch-Mode': 'cors',
        # 'Sec-Fetch-Site': 'same-origin',
        # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36',
        # 'X-Requested-With': 'XMLHttpRequest'
    }
    price_html = requests.get(
        f'https://hotel.alitrip.com/ajax/item.htm?item_id={item_id}&checkIn={check_in}&checkOut={check_out}',
        headers=header)
    html_json = json.loads(price_html.text)
    check_in = html_json['detail']['checkIn']
    check_out = html_json['detail']['checkOut']
    avgPrice = (html_json['detail']['avgPrice']) / 100  # 每日均价
    maxAvailRoomNum = html_json['detail']['maxAvailRoomNum']  # 房间最大人数
    minAvailRoomNum = html_json['detail']['minAvailRoomNum']  # 房间最小人数
    minusPrice = html_json['detail']['minusPrice']  # 优惠价格
    minusPriceTotal = html_json['detail']['minusPriceTotal']  # 总优惠价格
    nights = html_json['detail']['nights']  # 住宿夜晚

    rates = []
    for rate in html_json['detail']['rates']:
        room_price = (rate['avgPrice']) / 100  # 房间政策价格
        breakfast = rate['breakfast']  # 有无早餐
        cancelPolicy = rate['cancelPolicy']  # 退房政策
        room_name = rate['name']  # 政策名字
        rate_id = rate['rateid']
        payType = rate['payType']  # 付款类型
        totalOnlinePay = (rate['totalOnlinePay']) / 100  # 在线应支付总额
        rates.append({
            "room_price": floor(room_price),
            "breakfast": breakfast,
            "cancelPolicy": cancelPolicy,
            "room_name": room_name,
            "rate_id": rate_id,
            "payType": payType,
            "totalOnlinePay": floor(totalOnlinePay)  # 向下取整
        })

    data = {
        "code": 200,
        "check_in": check_in,
        "check_out": check_out,
        "avgPrice": floor(avgPrice - minusPrice),  # 每日最低价  减去单日优惠卷
        "maxAvailRoomNum": maxAvailRoomNum,  # 房间最大人数
        "minAvailRoomNum": minAvailRoomNum,  # 房间最小人数
        "minusPrice": minusPrice,  # 优惠价格
        "minusPriceTotal": minusPriceTotal,  # 总优惠价格
        "nights": nights,  # 住宿夜晚
        "retes": [rate for rate in rates]
    }

    return HttpResponse(json.dumps(data))


# except:
#     return HttpResponse(json.dumps({'msg': 'false', 'code': '400', 'ms': '连接失败，请重试'}))


def getPrices4Ump(request):
    rate_id = request.GET.get("rate_id")
    check_in = request.GET.get("check_in")
    check_out = request.GET.get("check_out")
    url = f'https://hotel.fliggy.com/ajax/getPrices4Ump.htm?rateId={rate_id}&checkIn={check_in}&checkOut={check_out}'
    html = requests.get(url)
    return HttpResponse(html.text)


# 匹配号码正则
def re_phone(text):
    phone = re.findall('电话.*\d', text)[0]
    return phone


# 酒店详细信息查询
def hotel_state(request):
    url = request.POST.get('hotel_url')
    shid = request.GET.get('shid')
    check_in = request.GET.get("check_in")
    check_out = request.GET.get("check_out")
    if not url:
        url = f'https://hotel.fliggy.com/hotel_detail2.htm?shid={shid}&checkIn={check_in}&checkOut={check_out}&_output_charset=utf8'
    headers_room = {
        'Host': 'hotel.fliggy.com',
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-User': '?1',
        'Sec-Fetch-Dest': 'document',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie':
            'cna=l5WNGNiqqSgCAdym5LAZ+BhD; UM_distinctid=1771d73d9d55e2-00b95bd216276e-31346d-1fa400-1771d73d9d6aa6; VISITED_HOTEL_TOKEN=b716af80-4bd3-4291-9a31-5046ea924896; t=bdd2901394b52a20f14c52c8abb23fd9; _tb_token_=fe7be4ee1388; cookie2=1a5cb4cd80068e1cf095fd230b5f55e9; chanelStat="NA=="; checkInDate=2021-03-19; checkOutDate=2021-03-20; dnk=%5Cu9686%5Cu5149%5Cu506552; hng=CN%7Czh-CN%7CCNY%7C156; tracknick=%5Cu9686%5Cu5149%5Cu506552; lid=%E9%9A%86%E5%85%89%E5%81%A552; CNZZDATA1253581663=647788943-1615283340-https%253A%252F%252Fhotel.fliggy.com%252F%7C1616564471; uc1=cookie21=VT5L2FSpdiNRFRLb&existShop=false&cookie16=UIHiLt3xCS3yM2h4eKHS9lpEOw%3D%3D&pas=0&cookie14=Uoe1hMHciuuR1g%3D%3D&cookie15=U%2BGCWk%2F75gdr5Q%3D%3D; _l_g_=Ug%3D%3D; unb=2618781971; cookie1=UITrVMMRckNCr5Og33A6a846OSqNi6HCH5%2BH70a%2BvfM%3D; login=true; cookie17=UU6gaQq%2BesRPOw%3D%3D; _nk_=%5Cu9686%5Cu5149%5Cu506552; sgcookie=E100Cew6G05%2FzIa1RyJ6kBLy8WwUe%2Fo%2B3Fh%2FuIirxOwQylNziCKWl32DU9vowAKFwHJHleYusQiERdK6ox248uqRgw%3D%3D; sg=21b; csg=00589699; enc=lu7VOLK8l0Yt2iS9QK6K6kueXZloEo0auoLt4g77BLxCKlJur4D4QlIdbJqAXILeBKvwnXsLPyyx3ljxwZd8lQ%3D%3D; xlly_s=1; tfstk=cEVAB_isfgjmXE388-Bk5chYCrblZ1stVEiM6Zno7SFRhDdOilF39JVdhVtxwaC..; x5sec=7b226873703b32223a223665653464323339316535323634353233386662333866363030633633663238434b6e4936344947454c4b342b4a72536a724f4858426f4d4d6a59784f4463344d546b334d5473784b4149776f4e62456a77593d222c22617365727665723b32223a223661316265633234376430396535346162643132316535353466323931386233434d624836344947454b66612f6f4c5369366d4374774561444449324d5467334f4445354e7a45374d5444756b764b3242513d3d227d; l=eBM9oNPgjjCSe_eEBOfZnurza77TtIRfguPzaNbMiOCPO8Cp5WAhW6wN5oT9CnGVns9HR3yf4eUaBx8sQy4edxv9-eOyMmJEEdLh.; isg=BDIyaPVWhhd727p2pffaXdHfg3gUwzZdRDDx2PwLF-XQj9OJ5FHrbETtfysz_671'
        # redis_cooke(14)
    }
    ajax = requests.get(url, headers=headers_room)
    html = etree.HTML(ajax.text)
    check_inh = html.xpath(".//*[@id='J_CheckInDate']/@value")[0]
    check_outh = html.xpath(".//*[@id='J_CheckOutDate']/@value")[0]
    hotel_text = html.xpath('//*[@id="hotel-desc"]/div[2]/text()')[0]
    phone = re_phone(hotel_text)
    lists = html.xpath('.//*[@id="J_RoomList"]')
    for list in lists:
        room_names = list.xpath('div/div/div[1]/div[3]/div/p[1]/span[1]/text()')  # 房间类型
        bed_types = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[1]/text()')  # 床型
        floor_spaces = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[2]/text()')  # 面积
        floors = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[3]/text()')  # 楼层
        windows = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[4]/text()')  # 窗口
        room_codes = list.xpath('div/div/div/div[1]/div/button/@data-srtid')  # 房型id
        status = list.xpath('div/div/div/div[1]/div/button/span/text()')  # 状态

    if len(floors) != len(room_names):
        for i in range(len(room_names)):
            floors.append('无')

    if len(windows) != len(room_names):
        for w in range(len(room_names)):
            windows.append('无')

    if len(bed_types) != len(room_names):
        for w in range(len(room_names)):
            bed_types.append('无')

    if len(floor_spaces) != len(room_names):
        for w in range(len(room_names)):
            floor_spaces.append('无')

    state = [
        {'room_name': room_name, 'bed_type': bed_type, 'floor_space': floor_space, 'floor': floor, 'window': window,
         'room_code': room_code, 'status': statu}
        for room_name, bed_type, floor_space, floor, window, room_code, statu in
        zip(room_names, bed_types, floor_spaces, floors, windows, room_codes, status)]

    data_json = {
        "result": 'true',
        "msg": "200",
        "data": {
            "check_in": check_inh,
            "check_out": check_outh,
            "contact": phone,
            "state": state
        },
    }
    return HttpResponse(json.dumps(data_json))


# 同行酒店报价查询
def hotel_peer_price(request):
    page_num = request.GET.get("page_num")
    room_code = request.GET.get("room_code")
    check_in = request.GET.get("check_in")
    check_out = request.GET.get("check_out")
    shid = request.GET.get("shid")
    header_sellers = {
        'authority': 'hotel.fliggy.com',
        'method': 'GET',
        # 'path': '/ajax/hotelDetailRT.htm?start=0&orderBy=0&orderDir=0&srtid=60441232&drid=&checkIn=2021-03-02&checkOut=2021-03-03&searchBy=&laterPay=false&isFreeCancel&isInstantConfirm&_ksTS=1614566001173_940&callback=jsonp941&shid=53964006&city=610100&urlType=1&biParam=no&sellerIds=&activityCode=&filterByRoomTickets=false&searchId=dae322cd2cd64295bfceaf06a43f6503&market=0',
        'scheme': 'https',
        'accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cookie':
            'cna=l5WNGNiqqSgCAdym5LAZ+BhD; UM_distinctid=1771d73d9d55e2-00b95bd216276e-31346d-1fa400-1771d73d9d6aa6; VISITED_HOTEL_TOKEN=b716af80-4bd3-4291-9a31-5046ea924896; t=bdd2901394b52a20f14c52c8abb23fd9; _tb_token_=fe7be4ee1388; cookie2=1a5cb4cd80068e1cf095fd230b5f55e9; chanelStat="NA=="; checkInDate=2021-03-19; checkOutDate=2021-03-20; dnk=%5Cu9686%5Cu5149%5Cu506552; hng=CN%7Czh-CN%7CCNY%7C156; tracknick=%5Cu9686%5Cu5149%5Cu506552; lid=%E9%9A%86%E5%85%89%E5%81%A552; uc1=cookie21=VT5L2FSpdiNRFRLb&existShop=false&cookie16=UIHiLt3xCS3yM2h4eKHS9lpEOw%3D%3D&pas=0&cookie14=Uoe1hMHciuuR1g%3D%3D&cookie15=U%2BGCWk%2F75gdr5Q%3D%3D; _l_g_=Ug%3D%3D; unb=2618781971; cookie1=UITrVMMRckNCr5Og33A6a846OSqNi6HCH5%2BH70a%2BvfM%3D; login=true; cookie17=UU6gaQq%2BesRPOw%3D%3D; _nk_=%5Cu9686%5Cu5149%5Cu506552; sgcookie=E100Cew6G05%2FzIa1RyJ6kBLy8WwUe%2Fo%2B3Fh%2FuIirxOwQylNziCKWl32DU9vowAKFwHJHleYusQiERdK6ox248uqRgw%3D%3D; sg=21b; csg=00589699; enc=lu7VOLK8l0Yt2iS9QK6K6kueXZloEo0auoLt4g77BLxCKlJur4D4QlIdbJqAXILeBKvwnXsLPyyx3ljxwZd8lQ%3D%3D; xlly_s=1; CNZZDATA1253581663=647788943-1615283340-https%253A%252F%252Fhotel.fliggy.com%252F%7C1616569871; x5sec=7b226873703b32223a223665653464323339316535323634353233386662333866363030633633663238434b6e4936344947454c4b342b4a72536a724f4858426f4d4d6a59784f4463344d546b334d5473784b4149776f4e62456a77593d222c22617365727665723b32223a2232353462313835636665383134353438633730643836353038363533303937304349585236344947454e4f6f6b2b535a2f64442b35674561444449324d5467334f4445354e7a45374e7967434d4f365338725946227d; tfstk=cFm1BJsAD1f61g8VbA9F0CANoSZVZPX7hFNiC4ODBG4GZSH1iiszNRnZosILyJ1..; l=eBM9oNPgjjCSe-F6BOfwhurza77OOIRfguPzaNbMiOCPOD1H5-0CW6wNudTMCnGVnsNWR3yf4eUaByLSkPU1lL9kklRyMmJE5dTh.; isg=BNjYdZ0gDOGmQSA4SzWAi6e9qQZqwTxLstLLlhLJFZPFrXmXutUP2TiL5eWdvfQj',
        'referer': 'https://hotel.fliggy.com/hotel_detail2.htm?spm=181.7087309.0.0.2da96354OFobs8&searchBy=&market=0&previousChannel=&shid=53964006&city=610100&checkIn=2021-03-24&checkOut=2021-03-25&searchId=dae322cd2cd64295bfceaf06a43f6503&filterByRoomTickets=false&activityCode=&roomNum=1&aNum_1=2&cNum_1=0&sellerId=&sellerIds=&_output_charset=utf8&_input_charset=utf8',
        'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest'
    }
    # &orderBy=price&orderDir=asc  价格降序
    seller = []
    ajax = requests.get(
        f'https://hotel.fliggy.com/ajax/hotelDetailRT.htm?start={page_num}&orderBy=price&orderDir=asc&srtid={room_code}&drid=&checkIn={check_in}&checkOut={check_out}&callback=jsonp1277&shid={shid}'
        , headers=header_sellers)
    ajax_data = ajax.text
    b = str(ajax_data[ajax_data.find('(') + 1: ajax_data.rfind(')')])
    html_json = json.loads(b)
    if html_json['code'] == 200:
        json_list = html_json['data']['items']
        for idata in json_list:
            if idata['isLianMeng'] == True:  # 是否直营
                lianmeng = '是'
            else:
                lianmeng = '否'
            seller_name = idata['sellerName']  # 运营商
            seller_id = idata['sellerId']  # 运营商编号
            describe = idata['sellerRoomPrices'][0]['sellerRoomTypeName']  # 房型
            price = idata['sellerRoomPrices'][0]['avgPriceWithOutTax']['amount']  # 价格
            policy = idata['sellerRoomPrices'][0]['refundDesc']  # 预定状态
            subscribe_type = idata['sellerRoomPrices'][0]['itemType']
            item_id = idata['sellerRoomPrices'][0]['itemId']  # 店铺房型id
            rate_id = idata['sellerRoomPrices'][0]['rateId']  # id
            breakfirst = idata['sellerRoomPrices'][0]['breakfirst']  # 早餐id
            total_subtract_amount = idata['sellerRoomPrices'][0]['totalSubtractAmount']  # 优惠价
            seller.append({
                "lianmeng": lianmeng,
                "seller_name": seller_name,
                "seller_id": seller_id,
                "describe": describe,
                # "price": round(price - total_subtract_amount, 2),   # 保留两位小数
                "price": floor(price - total_subtract_amount),  # 向下取整
                "policy": policy,
                "subscribe_type": subscribe_type,
                "breakfirst": breakfirst,
                "item_id": item_id,
                "rate_id": rate_id,
                "total_subtract_amount": total_subtract_amount  # 优惠政策 price 已减去
            }
            )

        data = {
            "code": 200,
            "page_num": page_num,
            "shid": shid,
            "room_code": room_code,
            "seller": [se for se in seller]
        }
        return HttpResponse(json.dumps(data))
    else:
        return HttpResponse(json.dumps({'msg': 'false', 'code': '400', 'ms': '请联系管理员'}))


def detail(request):
    url = request.POST.get('hotel_url')
    check_in = re.findall('checkIn=\d*-\d*-\d*', url)[0]
    check_out = re.findall('checkOut=\d*-\d*-\d*', url)[0]
    shid = re.findall('shid=\d*', url)[0]
    searchId = re.findall('searchId=[0-9a-z]*', url)[0]
    headers_room = {
        'Host': 'hotel.fliggy.com',
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-User': '?1',
        'Sec-Fetch-Dest': 'document',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie':
            'cna=l5WNGNiqqSgCAdym5LAZ+BhD; UM_distinctid=1771d73d9d55e2-00b95bd216276e-31346d-1fa400-1771d73d9d6aa6; VISITED_HOTEL_TOKEN=b716af80-4bd3-4291-9a31-5046ea924896; t=bdd2901394b52a20f14c52c8abb23fd9; _tb_token_=fe7be4ee1388; cookie2=1a5cb4cd80068e1cf095fd230b5f55e9; chanelStat="NA=="; checkInDate=2021-03-19; checkOutDate=2021-03-20; dnk=%5Cu9686%5Cu5149%5Cu506552; hng=CN%7Czh-CN%7CCNY%7C156; tracknick=%5Cu9686%5Cu5149%5Cu506552; lid=%E9%9A%86%E5%85%89%E5%81%A552; CNZZDATA1253581663=647788943-1615283340-https%253A%252F%252Fhotel.fliggy.com%252F%7C1616564471; uc1=cookie21=VT5L2FSpdiNRFRLb&existShop=false&cookie16=UIHiLt3xCS3yM2h4eKHS9lpEOw%3D%3D&pas=0&cookie14=Uoe1hMHciuuR1g%3D%3D&cookie15=U%2BGCWk%2F75gdr5Q%3D%3D; _l_g_=Ug%3D%3D; unb=2618781971; cookie1=UITrVMMRckNCr5Og33A6a846OSqNi6HCH5%2BH70a%2BvfM%3D; login=true; cookie17=UU6gaQq%2BesRPOw%3D%3D; _nk_=%5Cu9686%5Cu5149%5Cu506552; sgcookie=E100Cew6G05%2FzIa1RyJ6kBLy8WwUe%2Fo%2B3Fh%2FuIirxOwQylNziCKWl32DU9vowAKFwHJHleYusQiERdK6ox248uqRgw%3D%3D; sg=21b; csg=00589699; enc=lu7VOLK8l0Yt2iS9QK6K6kueXZloEo0auoLt4g77BLxCKlJur4D4QlIdbJqAXILeBKvwnXsLPyyx3ljxwZd8lQ%3D%3D; xlly_s=1; tfstk=cEVAB_isfgjmXE388-Bk5chYCrblZ1stVEiM6Zno7SFRhDdOilF39JVdhVtxwaC..; x5sec=7b226873703b32223a223665653464323339316535323634353233386662333866363030633633663238434b6e4936344947454c4b342b4a72536a724f4858426f4d4d6a59784f4463344d546b334d5473784b4149776f4e62456a77593d222c22617365727665723b32223a223661316265633234376430396535346162643132316535353466323931386233434d624836344947454b66612f6f4c5369366d4374774561444449324d5467334f4445354e7a45374d5444756b764b3242513d3d227d; l=eBM9oNPgjjCSe_eEBOfZnurza77TtIRfguPzaNbMiOCPO8Cp5WAhW6wN5oT9CnGVns9HR3yf4eUaBx8sQy4edxv9-eOyMmJEEdLh.; isg=BDIyaPVWhhd727p2pffaXdHfg3gUwzZdRDDx2PwLF-XQj9OJ5FHrbETtfysz_671'
        # redis_cooke(14)
    }
    ajax = requests.get(url, headers=headers_room)
    html = etree.HTML(ajax.text)
    check_inh = html.xpath(".//*[@id='J_CheckInDate']/@value")[0]
    check_outh = html.xpath(".//*[@id='J_CheckOutDate']/@value")[0]
    lists = html.xpath('.//*[@id="J_RoomList"]')
    for list in lists:
        room_names = list.xpath('div/div/div[1]/div[3]/div/p[1]/span[1]/text()')  # 房间类型
        bed_types = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[1]/text()')  # 床型
        floor_spaces = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[2]/text()')  # 面积
        floors = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[3]/text()')  # 楼层
        windows = list.xpath('div/div/div[1]/div[3]/div/p[2]/span[4]/text()')  # 窗口
        list_code = list.xpath('div/div/div/div[1]/div/button/@data-srtid')

    if len(floors) != len(room_names):
        for i in range(len(room_names)):
            floors.append('无')

    if len(windows) != len(room_names):
        for w in range(len(room_names)):
            windows.append('无')

    if len(bed_types) != len(room_names):
        for w in range(len(room_names)):
            bed_types.append('无')

    if len(floor_spaces) != len(room_names):
        for w in range(len(room_names)):
            floor_spaces.append('无')

    header_sellers = {
        'authority': 'hotel.fliggy.com',
        'method': 'GET',
        # 'path': '/ajax/hotelDetailRT.htm?start=0&orderBy=0&orderDir=0&srtid=60441232&drid=&checkIn=2021-03-02&checkOut=2021-03-03&searchBy=&laterPay=false&isFreeCancel&isInstantConfirm&_ksTS=1614566001173_940&callback=jsonp941&shid=53964006&city=610100&urlType=1&biParam=no&sellerIds=&activityCode=&filterByRoomTickets=false&searchId=dae322cd2cd64295bfceaf06a43f6503&market=0',
        'scheme': 'https',
        'accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cookie':
            'cna=l5WNGNiqqSgCAdym5LAZ+BhD; UM_distinctid=1771d73d9d55e2-00b95bd216276e-31346d-1fa400-1771d73d9d6aa6; VISITED_HOTEL_TOKEN=b716af80-4bd3-4291-9a31-5046ea924896; t=bdd2901394b52a20f14c52c8abb23fd9; _tb_token_=fe7be4ee1388; cookie2=1a5cb4cd80068e1cf095fd230b5f55e9; chanelStat="NA=="; checkInDate=2021-03-19; checkOutDate=2021-03-20; dnk=%5Cu9686%5Cu5149%5Cu506552; hng=CN%7Czh-CN%7CCNY%7C156; tracknick=%5Cu9686%5Cu5149%5Cu506552; lid=%E9%9A%86%E5%85%89%E5%81%A552; uc1=cookie21=VT5L2FSpdiNRFRLb&existShop=false&cookie16=UIHiLt3xCS3yM2h4eKHS9lpEOw%3D%3D&pas=0&cookie14=Uoe1hMHciuuR1g%3D%3D&cookie15=U%2BGCWk%2F75gdr5Q%3D%3D; _l_g_=Ug%3D%3D; unb=2618781971; cookie1=UITrVMMRckNCr5Og33A6a846OSqNi6HCH5%2BH70a%2BvfM%3D; login=true; cookie17=UU6gaQq%2BesRPOw%3D%3D; _nk_=%5Cu9686%5Cu5149%5Cu506552; sgcookie=E100Cew6G05%2FzIa1RyJ6kBLy8WwUe%2Fo%2B3Fh%2FuIirxOwQylNziCKWl32DU9vowAKFwHJHleYusQiERdK6ox248uqRgw%3D%3D; sg=21b; csg=00589699; enc=lu7VOLK8l0Yt2iS9QK6K6kueXZloEo0auoLt4g77BLxCKlJur4D4QlIdbJqAXILeBKvwnXsLPyyx3ljxwZd8lQ%3D%3D; xlly_s=1; CNZZDATA1253581663=647788943-1615283340-https%253A%252F%252Fhotel.fliggy.com%252F%7C1616569871; x5sec=7b226873703b32223a223665653464323339316535323634353233386662333866363030633633663238434b6e4936344947454c4b342b4a72536a724f4858426f4d4d6a59784f4463344d546b334d5473784b4149776f4e62456a77593d222c22617365727665723b32223a223934386662303331636331353062323035383035343337376237613834633535434e624d3634494745496e6a36366a4f2b626e6455686f4d4d6a59784f4463344d546b334d54737a4b41497737704c797467553d227d; isg=BGpqw8FV_n_20HLOrR8SJam3u9AM2-41zKi5gPQjO71IJwvh3GjBRMFRt1M712bN; tfstk=cv9hBQjNbB5CmaCMGv6BAUskkjlAZSwPoLJ6QLxdDbz6gQ9NiKFagfvijwYHe71..; l=eBM9oNPgjjCSeb0jBOfwhurza77OdIRfguPzaNbMiOCPOX5H5RyRW6wNJt8MCnGVnsT9R3yf4eUaBjLZEy4ehL9kklRyMmJEkdTh.',
        'referer': url,
        'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest'
        # redis_cooke(13)
    }

    seller = []

    for a in list_code:
        for p in range(8):
            ajax = requests.get(
                f'https://hotel.fliggy.com/ajax/hotelDetailRT.htm?start={p}&orderBy=price&orderDir=asc&srtid={a}&{check_in}&{check_out}&callback=jsonp1415&{shid}&{searchId}'
                , headers=header_sellers)
            time.sleep(1.5)
            ajax_data = ajax.text
            b = str(ajax_data[ajax_data.find('(') + 1: ajax_data.rfind(')')])
            html_json = json.loads(b)
            if html_json['code'] == 200:
                json_list = html_json['data']['items']
                for idata in json_list:
                    if idata['isLianMeng'] == True:  # 是否直营
                        lianmeng = '是'
                    else:
                        lianmeng = '否'
                    seller_name = idata['sellerName']  # 运营商
                    seller_id = idata['sellerId']  # 运营商编号
                    describe = idata['sellerRoomPrices'][0]['sellerRoomTypeName']  # 房型
                    price = idata['sellerRoomPrices'][0]['avgPriceWithOutTax']['amount']  # 价格
                    policy = idata['sellerRoomPrices'][0]['refundDesc']  # 预定状态
                    subscribe_type = idata['sellerRoomPrices'][0]['itemType']
                    item_id = idata['sellerRoomPrices'][0]['itemId']  # 店铺房型id
                    rate_id = idata['sellerRoomPrices'][0]['rateId']  # id
                    breakfirst = idata['sellerRoomPrices'][0]['breakfirst']  # 早餐id
                    total_subtract_amount = idata['sellerRoomPrices'][0]['totalSubtractAmount']  # 优惠价
                    seller.append({
                        "lianmeng": lianmeng,
                        "seller_name": seller_name,
                        "seller_id": seller_id,
                        "describe": describe,
                        # "price": round(price - total_subtract_amount, 2),   # 保留两位小数
                        "price": floor(price - total_subtract_amount),  # 向下取整
                        "policy": policy,
                        "subscribe_type": subscribe_type,
                        "breakfirst": breakfirst,
                        "item_id": item_id,
                        "rate_id": rate_id,
                        "total_subtract_amount": total_subtract_amount  # 优惠政策 price 已减去
                    })

                # subscribe_types.append(subscribe_type)
                # lianmengs.append(lianmeng)
                # seller_names.append(seller_name)
                # describes.append(describe)
                # prices.append(price)
                # policys.append(policy)

    # seller = [{"lianmeng": lianmeng,
    #            "seller_name": seller_name,
    #            "describe": describe,
    #            "price": price,
    #            "policy": policy,
    #            "subscribe_type": subscribe_type}
    #           for lianmeng, seller_name, describe, price, policy, subscribe_type
    #           in zip(lianmengs, seller_names, describes, prices, policys, subscribe_types)]

    room_list = [{"srtid": srtid,
                  "room_name": room_name,
                  "bed_type": bed_type,
                  "floor_space": floor_space,
                  "floor": floor,
                  "window": window,
                  "sellers": [se for se in seller if se['srtid'] == srtid]
                  }
                 for room_name, bed_type, floor_space, floor, window, srtid
                 in zip(room_names, bed_types, floor_spaces, floors, windows, list_code)]

    data_json = {
        "result": 'true',
        "msg": "200",
        "data": {
            "check_in": check_inh,
            "check_out": check_outh,
            "room_list": room_list
        },
    }

    return HttpResponse(json.dumps(data_json))
